package com.android.corestat.utils;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import android.annotation.SuppressLint;
import android.util.Log;

/**
 * 类说明：
 * 
 * @author Baker.li
 * @date 2014年4月21日
 * @version 1.0
 */

public class CryptUtil {
	private static final String TAG = CryptUtil.class.getSimpleName();
	private static final String KEY = "JY150811";

	@SuppressLint("TrulyRandom")
	public static String encrypt(String plain) throws Exception {
		SecureRandom sr = new SecureRandom();

		DESKeySpec dks = new DESKeySpec(KEY.getBytes("UTF-8"));

		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		SecretKey securekey = keyFactory.generateSecret(dks);
		Cipher cipher = Cipher.getInstance("DES");

		cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);

		byte[] encrypted = cipher.doFinal(plain.getBytes("UTF-8"));
		byte[] b = Base64.encode(encrypted, Base64.URL_SAFE);
		return new String(b, "UTF-8");
	}

	public static String getFileMD5(String fileName) {
		try {
			InputStream fis = new FileInputStream(fileName);
			byte[] buffer = new byte[1024 * 100];
			MessageDigest md5 = MessageDigest.getInstance("Md5");
			int numRead = 0;
			while ((numRead = fis.read(buffer)) > 0) {
				md5.update(buffer, 0, numRead);
			}
			fis.close();
			return toHexString(md5.digest());
		} catch (IOException ex) {
			Log.d(TAG, "IOException", ex);
		} catch (NoSuchAlgorithmException e) {
			Log.d(TAG, "NoSuchAlgorithmException", e);
		}
		return null;
	}

	private static String toHexString(byte[] b) {
		char[] hexChar = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

		StringBuilder sb = new StringBuilder(b.length * 2);
		for (int i = 0; i < b.length; i++) {
			sb.append(hexChar[(b[i] & 0xf0) >>> 4]);
			sb.append(hexChar[b[i] & 0x0f]);
		}
		return sb.toString();
	}
}
